/*
  This file is part of bnc.

  bnc is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  bnc is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with bnc.  If not, see <http://www.gnu.org/licenses/>.
*/
#include "./cryptor.h"

void cryptorConstructor(cryptor* aCryptor, char* aPassword, unsigned int aPasswordLength)
{
  for (aCryptor->pI=0; aCryptor->pI<256; aCryptor->pI++)
    aCryptor->pState[aCryptor->pI]=aCryptor->pI;

  for (aCryptor->pI=aCryptor->pJ=0; aCryptor->pI<256; aCryptor->pI++)
  {
    unsigned char lTemp;

    aCryptor->pJ=(aCryptor->pJ+aPassword[aCryptor->pI%aPasswordLength]+aCryptor->pState[aCryptor->pI])&255;
    lTemp=aCryptor->pState[aCryptor->pI];
    aCryptor->pState[aCryptor->pI]=aCryptor->pState[aCryptor->pJ];
    aCryptor->pState[aCryptor->pJ]=lTemp;
  }

  aCryptor->pI=aCryptor->pJ=0;
}

unsigned char cryptorCrypt(cryptor* aCryptor)
{
  unsigned char lTemp;

  aCryptor->pI=(aCryptor->pI+1)&255;
  aCryptor->pJ=(aCryptor->pJ+aCryptor->pState[aCryptor->pI])&255;

  lTemp=aCryptor->pState[aCryptor->pJ];
  aCryptor->pState[aCryptor->pJ]=aCryptor->pState[aCryptor->pI];
  aCryptor->pState[aCryptor->pI]=lTemp;

  return aCryptor->pState[(lTemp+aCryptor->pState[aCryptor->pJ])&255];
}
